<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="that js dude" content="">    
    <title>JS: Sorting Algorithm</title>

    <link rel="shortcut icon" href="images/favicon.jpg">    
    <link rel="stylesheet" href="css/bootstrap.min.css" >
    <link rel="stylesheet" href="css/zenburn.css">
    <!-- Custom styles for this template -->
    <style>
      /* Move down content because we have a fixed navbar that is 50px tall */
      body {        
        padding-bottom: 20px;
      }
      .purpleBold{
        color:purple;        
        font-weight: bold;
      }
      .gray{
        color: gray;
      }
      .blueish{
        color: rgba(151, 182, 209, 0.98);
      }
      .singInStuff{
        margin-top: 9px;
      }
      #uName{
        margin-top: -7px;
      }
      .skipListItem{
        list-style-type: none;
      }
      .skipListItem a{
        color: inherit;
      }
      a:visited
      { 
        color: rgba(218, 209, 149, 0.98);
      }
      .padding10Px{
        padding: 10px;
      }
      /*style for demo*/
      
    </style>

    <!-- Just for debugging purposes. Don't actually copy this line! -->
    <!--[if lt IE 9]><script src="docs-assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
  </head>
 
  <body>

    <!-- Main jumbotron for a primary marketing message or call to action -->
    <div class="jumbotron">
      <div class="container">
        <h1>JS: Interview Questions</h1>        
        <h4>Sort related interview questions for intermediate JavaScript developers</h4>
        <h2>Part-5: intermediate</h2>
        <p>June 29, 2014</p>
<!--         <div id="fb-root"></div><div class="fb-like" data-href="http://www.thatjsdude.com/interview/dom.html" data-layout="button_count" data-action="like" data-show-faces="false" data-share="false"></div><div class="g-plusone"></div> 
 -->      </div> 
    </div>
    <div class="container container-fluid">
      <!-- Example row of columns -->

      <div class="row center">        
        <!-- <iframe width="853" height="480" src="//www.youtube.com/embed/Rx_JFOSxgpY" frameborder="0" allowfullscreen></iframe> -->
      </div>
           
      <!-- <p class="gray">if you are little more comfortable or claim to be comfortable with javascript, these questions would not be enough for you. more coming</p>
      <p class="gray"> <span class="purpleBold">More Questions</span> <a href="css.html">css interview questions</a>, <a href="html.html">html interview questions</a> </p> -->
    <div id="questionList">
      <h2>Sorting Algorithm</h2>
      <ol>
        <li><a href="#bubbleSort">Bubble Sort</a> - explanation with tested code</li>
        <li><a href="#selectionSort">Selection Sort</a> - explanation with tested code</li>
        <li><a href="#insertionSort">Insertion Sort</a> - explanation with tested code</li>
        <li><a href="#mergeSort">Merger Sort</a> - explanation with tested code</li>
        <li><a href="#quickSort">Quick Sort</a> - explanation with tested code</li>
        <li><a href="#heapsort">Heap Sort</a> - explanation with tested code</li>
        <li><a href="#bucketSort">Bucket Sort</a></li>
        <li><a href="#shellSort">Shell Sort</a></li>
        <li><a href="#pigenholeSort">PigenHole Sort</a></li>
        <li><a href="#binaryTreeSort">BinaryTree Sort</a></li>
        <li><a href="#radixSort">Radix Sort</a></li>
        <li><a href="#cocktailSort">Cocktail Sort</a></li>
        <li><a href="#otherSort">Other Sort</a></li>
      </ol>
    </div>
    
      <div id="bubbleSort">
        <h2>Bubble Sort</h2>
        <p><strong>How it works:</strong></p>
        <p><strong>step-1:</strong> you compare the first item with the second. If the first item is bigger than the second item. you swap them so that the bigger one stays in the second position.</p>
        <p><strong>step-2:</strong>And then compare second with third item. if second item is bigger than the third, we swap them. otherwise, they stayed in their position. Hence, the biggest among first three is in the third position.</p>
        <p><strong>step-3:</strong>we keep doing it. until we hit the last element of the array. In that way we bubble up the biggest item of the array to the right most position of the array.</p>
        <p><strong>step-4:</strong> Look at the inner loop in the code below.</p>
        <p><strong>step-5:</strong> We repeat this process, starting from the last item of the array. look at the outer loop in the code below. We do this way, so that after finishing the first inner loop, the biggest one will be in the last item of the array.</p>
        <p><strong>step-6:</strong> and then we move backward inside the outer loop.</p>
        <p>same thing is going on....</p>
        <pre><code>
function bubbleSort(arr){
   var len = arr.length;
   for (var i = len-1; i>=0; i--){
     for(var j = 1; j<=i; j++){
       if(arr[j-1]>arr[j]){
           var temp = arr[j-1];
           arr[j-1] = arr[j];
           arr[j] = temp;
        }
     }
   }
   return arr;
}
bubbleSort([7,5,2,4,3,9]); //[2, 3, 4, 5, 7, 9]
bubbleSort([9,7,5,4,3,1]); //[1, 3, 4, 5, 7, 9]
bubbleSort([1,2,3,4,5,6]); //[1, 2, 3, 4, 5, 6]
        </code></pre>
        <p><strong>complexity:</strong></p>
      </div>   
      <div id="selectionSort">
        <h2>Selection Sort</h2>
        <p><strong>how does it works:</strong> This is very simple. Go through the array, find the index of the lowest element swap the lowest element with the first element. Hence first element is the lowest element in the array.</p>
        <p>Now go through the rest of the array (excluding the first element) and find the index of the lowest and swap it with the second element.</p>
        <p>thats how it continues to select (find out) the lowest element of the array and putting it on the left until it hits the last element.</p>
        <img src="images/selectionSort.png" alt="">        
        <pre><code>
function selectionSort(arr){
  var minIdx, temp, 
      len = arr.length;
  for(var i = 0; i &lt; len; i++){
    minIdx = i;
    for(var  j = i+1; j&lt;len; j++){
       if(arr[j]&lt;arr[minIdx]){
          minIdx = j;
       }
    }
    temp = arr[i];
    arr[i] = arr[minIdx];
    arr[minIdx] = temp;
  }
  return arr;
}
        </code></pre>
        <p><strong>complexity:</strong></p>
      </div>
      <div id="insertionSort">
        <h2>Insertion sort</h2>
        <p><strong>How it works: </strong> Imagine you are playing cards. Somebody is giving you cards one by one. When you are receiving card, you are planning to put them in a way so that the smaller one is on the left. This means you want to insert them in a sorted way</p>
        <p><strong>step-1:</strong> If the first card you are getting is 5. Just hold the card in your hand. you dont have to do anything. </p>
        <p><strong>step-2:</strong> If the second card is 2, you want to put it before 5 so that the two cards you have are sorted. When you are putting the card with number 2 at the left, you are changing the position of the card 5 from first position to second position. And then first position becomes available and you put 2 there.</p>
        <p><strong>step-3:</strong> If the third card is 4. you will start from second position. In the second position, you have card 5 which is bigger than 4. Hence you will move 5 to the third position. The next card to the left is 2 which is smaller than 4. Hence, you wont move 2. And you will insert card 4 in the second position.</p>
        <p><strong> step-4:</strong> Then you got 10. It is bigger than the previous card which is 5. Hence, you just add it at the last position.</p>
        <p><strong> step-5:</strong> The next card is 7. You just move the position of the card 10 to the right and insert card 7.</p>
        <p><strong> step-6:</strong> If the last card is 3. You will have to move 10 to the right as it is bigger than 3. and then you check with the next card to the left it is 7 which is bigger than 3. you move it to the right. similarly, you move 5, 4 to the right. And put the number 3 before 2 as 2 is smaller than 3.</p>
        <p>congrats. you are done.</p>
        <img src="images/insertionSort.png" alt="">
        <p><strong>Code Insertion sort</strong>: Code is similar to the card and image above. It starts with the second element. Pick the second element to be inserted and then compare to the previous element. If the first one is bigger, move the first one to second position and second one at first.</p>
        <p>Now first and second item is sorted.</p>
        <p>Then, pick the third element and check whether the second element is bigger than the third. keep going similar way until you hit the first element or a element smaller than the element you are comparing with. When you get an item smaller than the picked item, you insert it.</p>
        <p>super easy.</p>
        <pre><code>
function insertionSort(arr){
  var i, len = arr.length, el, j;

  for(i = 1; i&lt;len; i++){
    el = arr[i];
    j = i;

    while(j>0 && arr[j-1]>toInsert){
      arr[j] = arr[j-1];
      j--;
   }

   arr[j] = el;
  }

  return arr;
}
        </code></pre>
        <p><strong>complexity:</strong> the worst case O(n2) and best case O(n)</p>
      </div>
      <div id="mergeSort">
        <h2>Merge Sort</h2>
        <p>its a divide and conquer type algorithm. </p>
        <p>just break down your array into small and small pieces and until you have one items in each pieces. then merge together by comparing them. If you still have hard time to figure out what i am talking about, look at merge sort gif taken from wikipedia</p>
        <img src="images/mergeSort.gif" alt="">
        <p><strong>Code Merge Sort:</strong> Merge sort has two parts. Main part does divide or breaks down and second part is merging/combining parts. At the time of combining, parts are combined together.</p>
        <p><strong>Divide:</strong> the first function named as mergeSort is actually a divide function. where an array is divided into two.</p>
        <p><strong>merge:</strong> this is just merging two sorted array. Just be careful this two array could be in different size</p>
        <pre><code>
function mergeSort(arr){
   var len = arr.length;
   if(len &lt;2)
      return arr;
   var mid = Math.floor(len/2),
       left = arr.slice(0,mid),
       right =arr.slice(mid);
   //send left and right to the mergeSort to broke it down into pieces
   //then merge those
   return merge(mergeSort(left),mergeSort(right));
}
        </code></pre>
        <pre><code>
function merge(left, right){
  var result = [],
      lLen = left.length,
      rLen = right.length,
      l = 0,
      r = 0;
  while(l &lt; lLen && r &lt; rLen){
     if(left[l] &lt; right[r]){
       result.push(left[l++]);
     }
     else{
       result.push(right[r++]);
    }
  }  
  //remaining part needs to be addred to the result
  return result.concat(left.slice(l)).concat(right.slice(r));
}
        </code></pre>
        <p>ref: <a href="http://www.nczonline.net/blog/2012/10/02/computer-science-and-javascript-merge-sort/">merge sort</a></p>
      </div>
      <div id="quickSort">
        <h2>Quick sort</h2>
        <p><strong>how does it works:</strong></p>
        <p><strong>Step-1:</strong> You have to pick a pivot. This could be randomly selected or the middle one. Here we select the last element of the array.</p>
        <p><strong>Step-2:</strong> Put all the items smaller than the pivot value to the left and larger than the pivot value to the right.</p>
        <p><strong>Step-3:</strong>Repeat the step-2 for both left and right side of the pivot (pick a pivot, put all item smaller than the pivot to the left and larger on the right)</p>
        <h4>Explain the code</h4>
        <p><strong>Call Quick sort:</strong> Pass the array and pass left and right to the quickSort function. For the first call, left would be the index of the first element which is 0 and right would be the index of the last element which would be length -1.</p>
        <p><strong>Select Pivot:</strong> We select pivot as the last index of the array. </p>
        <p><strong>Call Partition function:</strong> After calculating the pivot, we send the pivot to the partition function. In the partition function we pass array, pivot index, left and right.</p>
        <p><strong>partitionIndex:</strong> In the partition function, we keep move all the items smaller than the pivot value to the left and larger than pivot value to the right. We have to keep track of the position of the partition. so that we can split the array into two parts in the next step. This tracking of the index where we partition the array is done by using partitionIndex variable. the initial value is left.</p>
        <p><strong>Swap function:</strong> This is just a helper function to swap values of the array.</p>
        <p><strong>move elements:</strong> we start a for loop from the left, and if the values is smaller than the pivot values we swap it with the position of the partitionIndex and increase the value of the partitionIndex. If the value is bigger, we don't do anything. We keep going until the element before the last element (remember last element is the pivot)</p>
        <p><strong>place pivot</strong> After moving all the smallest element to the left, we swap the last element (pivot value) with the partitionIndex. By doing this, the pivot sits where it suppose to sit when the full array is sorted. As all elements left to it smaller and all element right to it is bigger. End of the function partition, return the partitionIndex</p>
        <p><strong>Repeat the process: </strong>Now come back to quickSort function. when you get the partitionIndex, apply quickSort for the left side of the array and right side of the array. keep doing it until left is smaller than right.</p>
        <pre><code>
function quickSort(arr, left, right){
   var len = arr.length, 
   pivot,
   partitionIndex;


  if(left &lt; right){
    pivot = right;
    partitionIndex = partition(arr, pivot, left, right);
    
   //sort left and right
   quickSort(arr, left, partitionIndex - 1);
   quickSort(arr, partitionIndex + 1, right);
  }
  return arr;
}
        </code></pre>
        <pre><code>
function partition(arr, pivot, left, right){
   var pivotValue = arr[pivot],
       partitionIndex = left;

   for(var i = left; i &lt; right; i++){
    if(arr[i] &lt; pivotValue){
      swap(arr, i, partitionIndex);
      partitionIndex++;
    }
  }
  swap(arr, right, partitionIndex);
  return partitionIndex;
}
        </code></pre>
        <pre><code>
function swap(arr, i, j){
   var temp = arr[i];
   arr[i] = arr[j];
   arr[j] = temp;
}
        </code></pre>
        <img src="images/quickSort.png" alt="">
        <pre><code>
quickSort([11,8,14,3,6,2,7],0,6); 
//[2, 3, 6, 7, 8, 11, 14]
quickSort([11,8,14,3,6,2,1, 7],0,7);
//[1, 2, 3, 6, 7, 8, 11, 14]
quickSort([16,11,9,7,6,5,3, 2],0,7);
//[2, 3, 5, 6, 7, 9, 11, 16]
        </code></pre>
        <p>ref: <a href="https://gist.github.com/paullewis/1981455">quick sort</a></p>
        <p><strong>time complexity:</strong> talk about time complexity of quick sort</p>
      </div>
      <div id="heapSort">
        <h2>Heap sort</h2>        
        <p><strong>how does it works: </strong> first step is to build an heap. That is done in the heapify function. Hepaify put the largest element at the root.</p>
        <h2 class="text-danger">Add explanation for shiftDown</h2>
        <h2 class="text-warning">Add graphical description</h2>
        <p><a href="http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Weiss/L13-HeapSortEx.htm">Try to understand from here.</a> It doesn't have any code.</p>
        <pre><code>
function heapSort(arr){
  var len = arr.length,
      end = len-1;

  heapify(arr, len);
  
  while(end > 0){
   swap(arr, end--, 0);
   siftDown(arr, 0, end);
  }
  return arr;
}
        </code></pre>
        <pre><code>
function heapify(arr, len){
   // break the array into root + two sides, to create tree (heap)
   var mid = Math.floor((len-2)/2);
   while(mid >= 0){
    siftDown(arr, mid--, len-1);    
  }
}
        </code></pre>
        <pre><code>
function siftDown(arr, start, end){
   var root = start,
       child = root*2 + 1,
       toSwap = root;
   while(child <= end){
      if(arr[toSwap] &lt; arr[child]){
        swap(arr, toSwap, child);
      }
      if(child+1 <= end && arr[toSwap] &lt; arr[child+1]){
        swap(arr, toSwap, child+1)
      }
      if(toSwap != root){
         swap(arr, root, toSwap);
         root = toSwap;
      }
      else{
         return; 
      }
      toSwap = root;
      child = root*2+1
  }
}
        </code></pre>
        <pre><code>
function swap(arr, i, j){
  var temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}
        </code></pre>
        <p><strong>Question:</strong> Between merge and heap sort, which one you will choose?</p>
        <p><strong>compare with other:</strong><a href="http://en.wikipedia.org/wiki/Heapsort#Comparison_with_other_sorts">compare heap sort with others</a></p>        
      </div>
      <div id="bucketSort">
        <h2>Bucket Sort</h2>
        <p>bucket sort or bin sort. you partition the whole array into small buckets. put numbers in the related bucket and then sort each bucket by another algorithm or using bucket sort.</p>
        <p>for example, you have an array where numbers between 1 to 100 is for a million times.</p>
        <p>If you want to sort it by any of the method we talked before, will be time consuming.</p>
        <p>Bucket sort would be convenient here</p>
      </div>
      <div id="shellSort">
        <h2>Shell Sort</h2>
        <p><strong>how does it works: </strong> it takes a gap. for example gap of five. in that case it will take all the elements at 1, 6, 11, 16... and will sort them among themselves. Hence this gapped array will be sorted. secondly it will take 2, 7, 12, 17th positioned element and will sort among themselves</p>
        <p>second time. it will take all in three positioned. like 1, 4, 7, 10, 13, 16, 19 and will sort among themselves. after this all these will be sorted. and then goes to 2, 5, 8, 11, 14, 17, 20</p>
        <p>Then it will do 1 gap sorting... </p>
        <p>shell sort is rarely used in application as it performs more operations and have higher cache miss ratio than  quick sort. </p>
        <p>ref: <a href="http://en.wikipedia.org/wiki/Shell_sort">wiki: shell sort</a></p>
      </div>
      <div id="pigenholeSort">
        <h2>Pigeonhole Sort</h2>
        <p>also known as count sort (not counting sort). you have an array. and each element has a key value pair. you iterate over the original array and put each element based on the key to its small array (pigeon hole). and then iterate over the pigeonhole array in order.  </p>
        <p><strong>Counting sort: </strong> counting sort works same way, but it returns number of elements for each key other than the original elements. very thoughtful name, indeed.</p>
        <p>ref: <a href="http://en.wikipedia.org/wiki/Pigeonhole_sort">wiki pigeonhole sort</a></p>
      </div>
      <div id="binaryTreeSort">
        <h2>Binary Tree sort</h2>
      </div>
      <div id="radixSort">
        <h2>Radix Sort</h2>
        <p>its a non comparative integer sorting algorithm. it compares the integer based on the position of the number (significance). </p>
        <p>there are two radix sort. LSD (<a href="http://en.wikipedia.org/wiki/Radix_sort#An_example">least significant digit</a>) radix sort and MSD (<a href="http://en.wikipedia.org/wiki/Radix_sort#Most_significant_digit_radix_sorts">most significant digit</a>) radix sort</p>
      </div>
      <div id="cocktailSort">
        <h2>cocktail sort</h2>
        <p>also known as bidirectional bubble sort, cocktail shaker sort, shaker sort, ripple sort, shuffle sort, shuttle sort.</p>
        <p>difference with bubble sort is that this sort in both direction each pass. Its difficult to implement.</p>
      </div>
      <div id="otherSort">
        <h2>Other sorting algorithms</h2>
        <p><strong>patience sorting:</strong> sorting based on solitaire card game. you draw card either put in a new pile or existing pile. when you are putting card on a pile, a higher value card will go on top </p>
        <p><strong>comb sort: </strong> it is an improvement on bubble sort. the inner loop of bubble sort is modified so that gap between swapped elements goes down for each iteration of the outer loop by using a shrink factor. <a href="http://en.wikipedia.org/wiki/Comb_sort">wiki comb sort</a> the usual shrink factor is 1.3 and the gap (>=1) is calculated by <code>Math.floor(lenght/1.3)</code> </p>
        <p><strong>Spaghetti sort:</strong> it takes linear time but need parallel processor to sort. <a href="http://en.wikipedia.org/wiki/Spaghetti_sort">read it to understand</a></p>
        <p><strong>Intro sort:</strong>combines both quick sort and heap sort. so that worst and average becomes O(nlongn). it starts with quick sort and switch to heap sort if recursion depth increases based on the number of elements to be sorted.</p>
        <p><strong>Timsort: </strong> this is a hybrid of merge and insertion sort. try to find subset of data that is already sorted. and use that data to sort rest efficiently. and then merged by merge sort. this algorithm is primarily used in python. This actually invented by Tim peters to use in python.</p>
        <p><strong>Block sort: </strong>runs at least two merge operation with one insertion sort. <a href="http://en.wikipedia.org/wiki/Block_sort">wiki: block sort</a></p>
        <p><strong>library sort:</strong> it is an insertion sort with gaps in the array to improve insertion. <a href="http://en.wikipedia.org/wiki/Library_sort">wiki: library sort</a></p>
        <p><strong>Tournament sort: </strong> Its a selection sort with a priority queue to find the next element to sort. <a href="http://en.wikipedia.org/wiki/Tournament_sort">wiki: tournament sort</a></p>
        <p><strong>others: </strong><a href="http://en.wikipedia.org/wiki/Gnome_sort">Gnome sort</a>, <a href="http://en.wikipedia.org/wiki/UnShuffle_Sort">unshuffle sort</a>, <a href="http://en.wikipedia.org/wiki/Strand_sort">Strand sort</a>, <a href="http://en.wikipedia.org/wiki/Smoothsort">smooth sort</a></p>
      </div>
    <div>
      <h2>Need more:</h2>        
      <p>JavaScript part -1: <a href="js1.html">JS basic algorithm</a></p>
      <p>CSS: <a href="css.html">css related questions</a></p>
      <p>HTML: <a href="html.html">html related questions</a></p>
      <p><strong>Full list of interview questions are </strong><a href="https://github.com/khan4019/front-end-Interview-Questions">https://github.com/khan4019/front-end-Interview-Questions</a></p>
      <p>A lot of data structure, tree, graphs related interview questions are on the pipe line. Stay tuned</p>
    </div> 
    <div>
    <h2>References</h2>
    <ul>
      <li><a href="http://bigocheatsheet.com/">big o cheat sheet</a></li>      
      <li><a href="http://www.sorting-algorithms.com/">sort algorith animation</a></li>
      <li><a href="https://www.cs.cmu.edu/~adamchik/15-121/lectures/Sorting%20Algorithms/sorting.html">some sorting algorithm</a></li>      
    </ul>
  </div>
    <div>
      <h3 class="purpleBold">Express anger!</h3>        
      <!-- <p class="gray">Feel free to express your anger (sorry folks, you have to use g+.). Also point out my mistakes ( technical, wrong answer, spelling, grammar, sentence..., whatever), let your dude learn and grow.</p>
      <script src="https://apis.google.com/js/plusone.js"></script>
      <div class="g-comments"
          data-href="http://www.thatjsdude.com/interview/dom.html"
          data-width="642"
          data-first_party_property="BLOGGER"
          data-view_type="FILTERED_POSTMOD">
      </div>         -->
    </div>
      <hr>

      <footer>
        <p>&copy;thatJSDude 2014</p>
      </footer>
    </div> <!-- /container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="js/jquery-2.0.3.min.js"></script>    
    <script src="js/bootstrap.min.js"></script>
    <script src="js/highlight.pack.js"></script>    
    <script>hljs.initHighlightingOnLoad();</script>
    <script src="js/toggleExample.js"></script>
    <script type="text/javascript">
      // //social plugins
      // //g+
      // (function() {
      //   var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
      //   po.src = 'https://apis.google.com/js/platform.js';
      //   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
      // })();
      // //fb
      // (function(d, s, id) {
      //   var js, fjs = d.getElementsByTagName(s)[0];
      //   if (d.getElementById(id)) return;
      //   js = d.createElement(s); js.id = id;
      //   js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
      //   fjs.parentNode.insertBefore(js, fjs);
      // }(document, 'script', 'facebook-jssdk'));
    </script>
  </body>
</html>
